package caro.app.business;

import caro.app.protocolprovider.ProtocolProcessing;
import java.util.Iterator;
import java.util.List;

/**
 * Class Session
 * @author Thanh Nhan
 * @Since Aug 14, 2011
 * @Version 1.0
 */
public class Session extends Thread{
    private Board board = null;
    private Player player1 = null;
    private Player player2 = null;
    private int turn;
    public Session(Player player1, Player player2, int turn){
        this.player1 = player1;
        this.player2 = player2;
        board = new Board();
        this.turn = turn;
    }
    public Player getOpponent(String myUsername){
        if(player1.getName().equals(myUsername))
            return player2;
        else if(player2.getName().equals(myUsername))
            return player1;
        return null;
    }
    public Board getBoard(){
        return board;
    }
    public static boolean findPlayer(Player player, List<Session> sessions){
        Iterator<Session> iter = sessions.iterator();
        while(iter.hasNext()){
            Session session = iter.next();
            if(player.getName().equals(session.player1.getName()) 
                    || player.getName().equals(session.player2.getName()))
                return true;
        }
        return false;
    }
    public static Player findOpponent(String myUsername, List<Session> sessions){
        Iterator<Session> iter = sessions.iterator();
        while(iter.hasNext()){
            Session session = iter.next();
            if(myUsername.equals(session.player1.getName()))
                return session.player2;
            else if(myUsername.equals(session.player2.getName()))
                return session.player1;
        }
        return null;
    }
    public void changeTurn(){
        turn = 2/turn;
    }
    public void setCellValue(int r, int c, int v){
        board.check(r, c, v);
    }
    public void resetBoard(){
        board.reset();
    }
    @Override
    public boolean equals(Object o){
        if(o != null){
            if(o instanceof Session){
                Session tmp = (Session)o;
                return (tmp.player1.getName().equals(player1.getName()) &&
                        tmp.player2.getName().equals(player2.getName()));
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 53 * hash + (this.player1 != null ? this.player1.getName().hashCode() : 0);
        hash = 53 * hash + (this.player2 != null ? this.player2.getName().hashCode() : 0);
        return hash;
    }
}
